package com.wbl.train.business.controller.admin;
import cn.hutool.core.util.ObjectUtil;
import com.wbl.train.business.service.TrainSeatService;
import com.wbl.train.business.service.TrainService;
import com.wbl.train.common.business.dto.TrainDto;
import com.wbl.train.common.business.entity.TrainEntity;
import com.wbl.train.common.business.vo.TrainVo;
import com.wbl.train.common.exception.ApplicationException;
import com.wbl.train.common.page.PageVo;
import com.wbl.train.common.result.R;
import com.wbl.train.common.result.ResultCode;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 王博纶
 * @since 2024-02-01
 * @description 车次
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/admin/train")
@Tag(name = "车次控制器类",
        description = "TrainController 车次 后端数据接口")
public class TrainAdminController {
    private final TrainService trainService;
    private final TrainSeatService trainSeatService;

    /**
     * 通过id查询 火车车次
     * @return Result
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/query_all")
    public R<List<TrainVo>> getAll() {
        List<TrainVo> trainVos = trainService.queryAllTrain();
        return R.ok("查询成功",trainVos);
    }

    /**
     * 通过id查询 火车车次
     * @param trainDto 火车车次Dto
     * @return Result
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/query")
    public R<PageVo<TrainEntity>> getById(TrainDto trainDto) {
        // 火车车次查询
        log.debug("trainDto :{}",trainDto);
        PageVo<TrainEntity> pageVo = trainService.queryTrain(trainDto);
        return R.ok("查询成功",pageVo);
    }

    /**
     * 新增 车次
     * @param train 车次
     * @return Result
     */
    @Operation(summary = "新增车次", description = "新增车次")
    @PostMapping("/save")
    public R<Boolean> save(@Valid @RequestBody TrainEntity train) {
        return R.ok("保存成功",trainService.insertAndUpdateTrain(train));
    }


    /**
     * 通过id删除 车次
     * @param id id
     * @return Result
     */
    @Operation(summary = "通过id删除车次",
               description = "通过id删除车次")
    @DeleteMapping("/delete/{id}")
    public R<Boolean> removeById(@PathVariable Long id) {
        if(ObjectUtil.isNull(trainService.getById(id))){
            throw new ApplicationException(ResultCode.DATA_NOT_EXIST,"当前火车车次不存在");
        }
        return R.ok(trainService.removeById(id));
    }

    @Operation(summary = "生成车厢和座位",
            description = "生成车厢和座位")
    @GetMapping("/generate-seat/{trainCode}")
    public void generateCarriageAndSeat(@PathVariable String trainCode){
        trainSeatService.generateSeat(trainCode);
    }
}
